from typing import List, Dict, Any
import numpy as np
import pandas as pd
from .agent import Agent
import random

class OpinionModel:
    def __init__(self, config: Dict[str, Any]):
        self.config = config
        # 设置随机种子
        np.random.seed(config.get("random_seed", 42))
        random.seed(config.get("random_seed", 42))
        
        # 加载处理后的数据
        self.user_features = pd.read_csv('data/processed/user_features.csv')
        self.group_clusters = pd.read_csv('data/processed/group_clusters.csv')
        self.sentiment_data = pd.read_csv('data/processed/sentiment_analysis.csv')
        
        self.num_agents = len(self.user_features)
        self.num_groups = len(self.group_clusters)
        self.network_density = config.get("network_density", 0.1)
        self.agents: List[Agent] = []
        self.network = self._initialize_network()
        self.initialize_agents()
        
    def _initialize_network(self) -> np.ndarray:
        """初始化社交网络"""
        network = np.zeros((self.num_agents, self.num_agents))
        # 同组用户之间连接概率更高
        for i in range(self.num_agents):
            for j in range(i+1, self.num_agents):
                group_i = self.user_features.iloc[i]['group_id']
                group_j = self.user_features.iloc[j]['group_id']
                # 同组用户连接概率更高
                if group_i == group_j:
                    if np.random.random() < self.network_density * 1.5:
                        network[i][j] = network[j][i] = 1
                else:
                    if np.random.random() < self.network_density:
                        network[i][j] = network[j][i] = 1
        return network
        
    def initialize_agents(self) -> None:
        """从数据文件初始化智能体"""
        for _, user in self.user_features.iterrows():
            agent = Agent(
                agent_id=user['user_id'],
                group_id=user['group_id'],
                initial_opinion=user['opinion_tendency'],
                activity_score=user['activity_score'],
                influence_score=user['influence_score'],
                emotional_stability=user['emotional_stability']
            )
            self.agents.append(agent)
            
    def get_neighbors(self, agent_id: int) -> List[Agent]:
        """获取智能体的邻居"""
        # 确保 agent_id 是整数
        agent_idx = int(agent_id) - 1
        neighbor_indices = np.where(self.network[agent_idx] == 1)[0]
        return [self.agents[i] for i in neighbor_indices]
        
    def step(self) -> Dict[str, Any]:
        """执行一个时间步的模拟"""
        for agent in self.agents:
            neighbors = self.get_neighbors(agent.agent_id)
            if not neighbors:
                continue
                
            # 观察邻居
            observation = agent.observe_neighbors(neighbors)
            
            # 计算社交压力
            social_pressure = agent.calculate_social_pressure(observation["avg_opinion"])
            
            # 更新观点
            agent.update_opinion(social_pressure)
            
            # 决定是否表达观点
            if agent.decide_to_speak():
                # 记录观点表达
                self._record_opinion_expression(agent)
                
        return self.get_model_state()
        
    def _record_opinion_expression(self, agent: Agent) -> None:
        """记录观点表达"""
        # 这里可以添加观点表达记录的逻辑
        pass
        
    def get_model_state(self) -> Dict[str, Any]:
        """获取模型当前状态"""
        return {
            "agents": [agent.get_state() for agent in self.agents],
            "network": self.network.tolist(),
            "num_agents": self.num_agents,
            "num_groups": self.num_groups,
            "network_density": self.network_density
        } 